package com.woniu.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    @Bean
    public Queue messageShop(){
        return new Queue("message-shop");
    }

    @Bean
    public Queue messageBack(){
        return new Queue("message-back");
    }

    @Bean
    public Exchange complainFanout(){
        return new FanoutExchange("complain-fanout");
    }

    @Bean
    public Binding complainBinding(@Qualifier("messageShop")Queue queue,
                                   @Qualifier("complainFanout")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("message").noargs();
    }

    @Bean
    public Binding complainBindings(@Qualifier("messageBack")Queue queue,
                                   @Qualifier("complainFanout")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("message").noargs();
    }

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitAdmin rabbitAdmin(
            ConnectionFactory factory,
            Exchange complainFanout,
            Queue messageBack,
            Queue messageShop) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.declareExchange(complainFanout);
        rabbitAdmin.declareQueue(messageBack);
        rabbitAdmin.declareQueue(messageShop);
        return rabbitAdmin;
    }
}
